<?php

namespace app\api\controller;


use app\api\model\UserAddress;
use app\common\controller\Api;

/**
 * 用户地址接口
 */
class Address extends Api
{
    //protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    //地址列表
    public function lists()
    {
        $list = UserAddress::where(['user_id'=>$this->auth->id])->select();
        $this->success('',$list);
    }

    /**
     * 添加编辑地址
     *
     */
    public function addedit()
    {
        $id = input('id',0);
        $realname = input('realname','');
        $mobile = input('mobile','');
        $lat = input('lat','');
        $lng = input('lng','');
        $address = input('address','');
        $is_default = input('is_default',0);

        $data = [
            'address'     => $address,
            'is_default'   => $is_default,
            'mobile'      => $mobile,
            'realname'    => $realname,
            'lat'     => $lat,
            'user_id'     => $this->auth->id,
            'lng'     => $lng,
        ];
        if ($is_default==1){
            UserAddress::where(['user_id'=>$this->auth->id])->update(['is_default'=>0]);
        }

        if ($id) { //编辑
            $row = UserAddress::where('id', $id)->where('user_id', $this->auth->id)->find();
            if (!$row) {
                $this->error('未找到记录');
            }
            $row->save($data);
        } else { //添加
            (new UserAddress)->save($data);
        }
        $this->success('操作成功');
        $this->success('请求成功');
    }


    //地址信息
    public function detail()
    {
        $id = input('id',0);
        if (!$id) {
            $this->error('参数错误');
        }

        $detail = UserAddress::get($id);
        $this->success('',$detail);
    }

    //删除地址
    public function del()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('参数错误');
        }
        $row = UserAddress::where('user_id', $this->auth->id)->where('id', $id)->find();
        if (!$row) {
            $this->error('未找到记录');
        }
        $row->delete();
        $this->success('删除成功');
    }

    //设置默认
    public function setdefault()
    {
        $id = input('id',0);
        if (!$id) {
            $this->error('参数错误');
        }

        UserAddress::where(['user_id'=>$this->auth->id])->update(['is_default'=>0]);

        UserAddress::where(['user_id'=>$this->auth->id,'id'=>$id])->update(['is_default'=>1]);
        $this->success('设置成功');
    }
}
